package com.agile.leetcode.scanPackage;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author ChenZhangKun
 * @Date 2020/12/4 9:41
 */
public class ScanPackage {
    // 定义集合存储
    List<String> classPaths = new ArrayList<>(10);
    Map<String, Object> beans = new HashMap<>(16);

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        ScanPackage scanPackage = new ScanPackage();
        List<String> list = scanPackage.scanPackage("com.agile.leetcode");
        System.out.println(list);
        scanPackage.doInstance();
    }

    /**
     * 扫描所有的类
     *
     * @param basePackage
     * @return
     */
    private List<String> scanPackage(String basePackage) {
        // 拿到类加载器加载
        URL url = this.getClass().getClassLoader().getResource(basePackage.replaceAll("\\.", "/"));
        // 拿到文件地址
        if (url != null) {
            String fileStr = url.getFile();
            // 转为文件
            File file = new File(fileStr);
            // 获取里面所有文件
            String[] list = file.list();
            if (list != null) {
                // 遍历
                for (String s : list) {
                    // 转为文件
                    File file1 = new File(fileStr + "/" + s);
                    // 是目录，则递归
                    if (file1.isDirectory()) {
                        scanPackage(basePackage + "." + s);
                    } else {
                        classPaths.add(basePackage + "." + s);
                    }
                }
            }
        }
        return classPaths;
    }

    public void doInstance() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        // 遍历集合
        for (String classPath : classPaths) {
            // 去掉.class
            String s = classPath.replaceAll(".class", "");
            // 反射拿到字节码
            Class<?> clazz = Class.forName(s);
            // 拿到其类名
            String simpleName = clazz.getSimpleName();
            // 反射执行
            Object o = clazz.newInstance();
            // 放入集合
            beans.put(simpleName, o);
        }
    }
}
